package com.fenxiangtech.mall.controller;

import com.alibaba.fastjson.JSON;
import com.fenxiangtech.mall.base.BaseResponse;
import com.fenxiangtech.mall.base.PageData;
import com.fenxiangtech.mall.manager.AreaManager;
import com.fenxiangtech.mall.model.Area;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixiang
 * @CreateTime 2018/10/27
 **/
@Controller
public class AreaController extends AbstractBaseController {
    @Autowired
    private AreaManager areaManager;

    @GetMapping("/area/query")
    @ResponseBody
    public BaseResponse<PageData<Area>> queryArea(Area area, Integer pageIndex , Integer pageSize){

        List<Area> areas = areaManager.queryArea(area, pageIndex, pageSize);
        Long totalCount = areaManager.countArea(area);

        pageIndex = pageIndex == null?1:pageIndex;
        pageSize = pageSize == null?20:pageSize;
        return  BaseResponse.assemblePageResponse(areas,totalCount,pageIndex,pageSize);
    }

    @PostMapping("/area/save")
    @ResponseBody
    public BaseResponse<String> saveItem(Area area){
        BaseResponse<String> baseResponse = new BaseResponse<>();
        areaManager.saveArea(area);
        baseResponse.setData("OK");
        return  baseResponse;
    }

    @GetMapping("/area/list")
    @ResponseBody
    public String listItem(Area area, Integer pageNumber , Integer pageSize){

        Map<String,Object> map  = new HashMap<>();

        List<Area> areas = areaManager.queryArea(area, pageNumber, pageSize);
        Long totalCount = areaManager.countArea(area);
        map.put("total",totalCount);
        map.put("rows",areas);
        return JSON.toJSONString(map);
    }
    
    @GetMapping("/area/get")
    @ResponseBody
    public Area listItem(Area area){

        List<Area> areas = areaManager.queryArea(area, 1, 1);
        if(areas!=null && areas.size()>0){
            return areas.get(0);
        }else{
            return new Area();
        }
    }

    @GetMapping("/area/delete")
    @ResponseBody
    public String delete(Long id){
        areaManager.deleteArea(id);
        return "OK";
    }

}
